package com.jxauaia.contest.service.impl;

import com.jxauaia.contest.common.exception.BusinessException;
import com.jxauaia.contest.mapper.UserMapper;
import com.jxauaia.contest.model.dto.ChangePasswordDTO;
import com.jxauaia.contest.model.dto.LoginDTO;
import com.jxauaia.contest.model.dto.RegisterDTO;
import com.jxauaia.contest.model.dto.UserProfileDTO;
import com.jxauaia.contest.model.dto.PersonalPageDTO;
import com.jxauaia.contest.model.entity.User;
import com.jxauaia.contest.model.vo.CaptchaVO;
import com.jxauaia.contest.service.CaptchaService;
import com.jxauaia.contest.service.FileService;
import com.jxauaia.contest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;
    private final PasswordEncoder passwordEncoder;
    private final CaptchaService captchaService;
    private final FileService fileService;

    @Autowired
    public UserServiceImpl(UserMapper userMapper, PasswordEncoder passwordEncoder,
                           CaptchaService captchaService, FileService fileService) {
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
        this.captchaService = captchaService;
        this.fileService = fileService;
    }

    @Override
    @Transactional
    public User register(RegisterDTO registerDTO) {
        // 验证验证码
        if (registerDTO.getCaptchaId() != null && registerDTO.getCaptchaCode() != null) {
            boolean captchaValid = validateCaptcha(registerDTO.getCaptchaId(), registerDTO.getCaptchaCode());
            if (!captchaValid) {
                throw new BusinessException("验证码错误或已过期");
            }
        }

        // 检查用户名是否已存在
        if (existsByUsername(registerDTO.getUsername())) {
            throw new BusinessException("用户名已存在");
        }

        // 检查邮箱是否已存在
        if (existsByEmail(registerDTO.getEmail())) {
            throw new BusinessException("邮箱已被注册");
        }

        // 创建新用户
        User user = new User();
        user.setUsername(registerDTO.getUsername());
        user.setEmail(registerDTO.getEmail());

        // 密码加密
        user.setPassword(passwordEncoder.encode(registerDTO.getPassword()));

        // 设置默认值
        user.setUserType("member");
        user.setStatus(1);

        // 设置证件类型和证件号
        user.setIdType(registerDTO.getIdType());
        user.setIdNumber(registerDTO.getIdNumber());

        // 分配随机头像
        user.setAvatar(fileService.getRandomAvatar());
        // 设置创建时间和更新时间
        Date now = new Date();
        user.setCreateTime(now);
        user.setUpdatedTime(now);

        // 保存用户
        userMapper.insert(user);

        return user;
    }

    @Override
    public User login(LoginDTO loginDTO) {
        // 验证验证码
        if (loginDTO.getCaptchaId() != null && loginDTO.getCaptchaCode() != null) {
            boolean captchaValid = validateCaptcha(loginDTO.getCaptchaId(), loginDTO.getCaptchaCode());
            if (!captchaValid) {
                throw new BusinessException("验证码错误或已过期");
            }
        }

        // 查找用户（支持用户名或邮箱登录）
        User user = userMapper.findByUsername(loginDTO.getUsername());
        if (user == null) {
            user = userMapper.findByEmail(loginDTO.getUsername());
        }

        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        // 验证密码
        if (!passwordEncoder.matches(loginDTO.getPassword(), user.getPassword())) {
            throw new BusinessException("密码错误");
        }

        // 检查用户状态
        if (user.getStatus() != 1) {
            throw new BusinessException("账号已被禁用");
        }

        // 不返回密码
        user.setPassword(null);
        return user;
    }

    @Override
    public User findById(Integer id) {
        return userMapper.findById(id);
    }

    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    public User findByEmail(String email) {
        return userMapper.findByEmail(email);
    }

    @Override
    public List<User> findAll() {
        List<User> users = userMapper.findAll();
        // 不返回密码
        for (User user : users) {
            user.setPassword(null);
        }
        return users;
    }

    @Override
    public boolean save(User user) {
        // 加密密码
        if (user.getPassword() != null && !user.getPassword().isEmpty()) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }

        if (user.getId() == null) {
            // 新增用户
            return userMapper.insert(user) > 0;
        } else {
            // 更新用户
            return userMapper.update(user) > 0;
        }
    }

    @Override
    @Transactional
    public User updateUserProfile(Integer userId, UserProfileDTO userProfileDTO) {
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        // 更新用户信息
        if (userProfileDTO.getAvatar() != null) {
            user.setAvatar(userProfileDTO.getAvatar());
        }
        if (userProfileDTO.getUserProfile() != null) {
            user.setUserProfile(userProfileDTO.getUserProfile());
        }
        if (userProfileDTO.getMajor() != null) {
            user.setMajor(userProfileDTO.getMajor());
        }
        if (userProfileDTO.getQqNumber() != null) {
            user.setQqNumber(userProfileDTO.getQqNumber());
        }
        if (userProfileDTO.getPhoneNumber() != null) {
            user.setPhoneNumber(userProfileDTO.getPhoneNumber());
        }
        if (userProfileDTO.getRealName() != null) {
            user.setRealName(userProfileDTO.getRealName());
        }
        // 添加university字段处理
        if (userProfileDTO.getUniversity() != null) {
            user.setUniversity(userProfileDTO.getUniversity());
        }

        user.setUpdatedTime(new Date());
        userMapper.updateUserProfile(user);

        // 不返回密码
        user.setPassword(null);
        return user;
    }

    @Override
    @Transactional
    public boolean changePassword(Integer userId, ChangePasswordDTO changePasswordDTO) {
        // 验证新密码和确认密码是否一致
        if (!changePasswordDTO.getNewPassword().equals(changePasswordDTO.getConfirmPassword())) {
            throw new BusinessException("新密码和确认密码不一致");
        }

        User user = userMapper.findById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        // 验证旧密码
        if (!passwordEncoder.matches(changePasswordDTO.getOldPassword(), user.getPassword())) {
            throw new BusinessException("旧密码不正确");
        }

        // 更新密码
        String encodedPassword = passwordEncoder.encode(changePasswordDTO.getNewPassword());
        Date now = new Date();
        int result = userMapper.updatePassword(userId, encodedPassword, now);

        return result > 0;
    }

    @Override
    public boolean deleteUser(Integer id) {
        return userMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional
    public boolean deactivateAccount(Integer userId, Integer currentUserId) {
        // 验证权限（只能注销自己的账号或管理员可以注销任何账号）
        User currentUser = userMapper.findById(currentUserId);
        if (currentUser == null) {
            throw new BusinessException("当前用户不存在");
        }

        // 如果不是管理员且不是注销自己的账号，则拒绝操作
        if (!currentUser.getUserType().equals("admin") && !userId.equals(currentUserId)) {
            throw new BusinessException("没有权限执行此操作");
        }

        // 执行软删除（将状态设置为禁用）
        Date now = new Date();
        int result = userMapper.disableUser(userId, now);

        return result > 0;
    }

    @Override
    @Transactional
    public boolean updateStatus(Integer userId, Integer status) {
        if (status != 0 && status != 1) {
            throw new BusinessException("无效的状态值");
        }

        User user = userMapper.findById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        Date now = new Date();
        int result = userMapper.updateStatus(userId, status, now);

        return result > 0;
    }

    @Override
    public boolean existsByUsername(String username) {
        return userMapper.countByUsername(username) > 0;
    }

    @Override
    public boolean existsByEmail(String email) {
        return userMapper.countByEmail(email) > 0;
    }

    @Override
    public User getUserById(Long id) {
        if (id == null) {
            return null;
        }
        // 将Long类型转换为Integer类型
        return findById(id.intValue());
    }

    @Override
    public User getUserByUsername(String username) {
        return findByUsername(username);
    }

    @Override
    public boolean createUser(User user) {
        return save(user);
    }

    @Override
    public boolean updateUser(User user) {
        if (user == null || user.getId() == null) {
            return false;
        }
        return save(user);
    }

    @Override
    public boolean deleteUser(Long id) {
        if (id == null) {
            return false;
        }
        // 将Long类型转换为Integer类型
        return deleteUser(id.intValue());
    }

    @Override
    public CaptchaVO generateCaptcha() {
        try {
            // 直接返回CaptchaService生成的验证码对象
            return captchaService.generateCaptcha();
        } catch (Exception e) {
            throw new BusinessException("生成验证码失败: " + e.getMessage());
        }
    }

    @Override
    public boolean validateCaptcha(String captchaId, String captchaCode) {
        return captchaService.validate(captchaId, captchaCode);
    }
    
    // 将类外部的方法移到这里
    @Override
    public User getUserPersonalPage(Integer userId) {
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        // 出于安全考虑，不返回密码
        user.setPassword(null);
        return user;
    }

    @Override
    @Transactional
    public User updateUserPersonalPage(Integer userId, UserProfileDTO userProfileDTO) {
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        // 更新用户资料
        if (userProfileDTO.getAvatar() != null) {
            user.setAvatar(userProfileDTO.getAvatar());
        }
        if (userProfileDTO.getUserProfile() != null) {
            user.setUserProfile(userProfileDTO.getUserProfile());
        }
        if (userProfileDTO.getMajor() != null) {
            user.setMajor(userProfileDTO.getMajor());
        }
        if (userProfileDTO.getQqNumber() != null) {
            user.setQqNumber(userProfileDTO.getQqNumber());
        }
        if (userProfileDTO.getPhoneNumber() != null) {
            user.setPhoneNumber(userProfileDTO.getPhoneNumber());
        }
        if (userProfileDTO.getRealName() != null) {
            user.setRealName(userProfileDTO.getRealName());
        }
        if (userProfileDTO.getUniversity() != null) {
            user.setUniversity(userProfileDTO.getUniversity());
        }

        user.setUpdatedTime(new Date());
        userMapper.updateUserProfile(user);

        // 不返回密码
        user.setPassword(null);
        return user;
    }

    @Override
    @Transactional
    public boolean cancelAccount(Integer userId, String password) {
        User user = userMapper.findById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        // 验证密码
        if (!passwordEncoder.matches(password, user.getPassword())) {
            throw new BusinessException("密码错误，无法注销账号");
        }

        // 彻底删除用户账号
        return userMapper.deleteById(userId) > 0;
    }

    @Override
    public boolean resetPassword(Integer userId, String newPassword) {
        User user = userMapper.findById(userId);
        if (user == null) {
            return false;
        }
        
        // 加密新密码
        String encodedPassword = passwordEncoder.encode(newPassword);
        user.setPassword(encodedPassword);
        
        // 更新密码
        Date now = new Date(); // 添加当前时间
        int result = userMapper.updatePassword(userId, encodedPassword, now); // 修改为三个参数
        return result > 0;
    }

    @Override
    public List<User> searchUsers(String username, String email, String realName, Integer status) {
        // 构建查询条件
        Map<String, Object> params = new HashMap<>();
        
        if (StringUtils.hasText(username)) {
            params.put("username", username);
        }
        
        if (StringUtils.hasText(email)) {
            params.put("email", email);
        }
        
        if (StringUtils.hasText(realName)) {
            params.put("realName", realName);
        }
        
        if (status != null) {
            params.put("status", status);
        }
        
        // 调用Mapper进行查询
        List<User> users = userMapper.searchUsers(params);
        // 不返回密码
        for (User user : users) {
            user.setPassword(null);
        }
        return users;
    }
}